package com.gzyz.cheetah.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.gzyz.cheetah.entity.dto.CommentDTO;
import com.gzyz.cheetah.entity.dto.PageDTO;
import com.gzyz.cheetah.entity.table.Comment;
import com.gzyz.cheetah.entity.table.SensitiveWord;
import com.gzyz.cheetah.mapper.CommentMapper;
import com.gzyz.cheetah.service.ICommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author xclhove
 * @since 2023-11-06
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    private final CommentMapper commentMapper;
    
    @Override
    public boolean addComment(Comment comment) {
        List<SensitiveWord> sensitiveWords = Db.list(SensitiveWord.class);
        String content = comment.getContent();
        for (SensitiveWord sensitiveWord : sensitiveWords) {
            String sensitiveWordWord = sensitiveWord.getWord();
            content = content.replaceAll(sensitiveWordWord, "**");
        }
        comment.setContent(content);
        return this.save(comment);
    }
    
    @Override
    public boolean deleteCommentById(Integer commentId) {
        return this.removeById(commentId);
    }
    
    @Override
    public boolean updateComment(Comment comment) {
        comment.setUpdateTime(LocalDateTime.now());
        return this.updateById(comment);
    }
    
    @Override
    public PageDTO<CommentDTO> pageDocumentComments(Integer documentId, Integer pageNo, Integer pageSize) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getDocumentId,documentId);
        int total = this.list(lambdaQueryWrapper).size();
        List<CommentDTO> commentDTOS = commentMapper.pageDocumentComments(documentId, ((pageNo - 1) * pageSize), pageSize);
        PageDTO<CommentDTO> pageDTO = new PageDTO<>(total, commentDTOS);
        return pageDTO;
    }
}
